package com.shou.zhnfyxt.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.shou.zhnfyxt.service.OssUploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class OssUploadServiceImpl implements OssUploadService {
    @Override
    public String uploadFile(MultipartFile multipartFile, String dir) {
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        String accessKeyId = "LTAI5tKqDq4HjvVTRL1Uigcg";
        String accessKeySecret = "OPpkrPJf3pKGkGVY2vaOCNswJqmQgP";
        String bucketName = "zhnfyxt";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        try {
//            // 创建OSSClient实例。
//            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
//            //判断桶是否存在，不存在则创建桶
//            if(!ossClient.doesBucketExist(bucketName)){
//                //创建bucket
//                ossClient.createBucket(bucketName);
//                //设置oss实例的访问权限：公共读
//                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
//            }
//            //获取文件上传的流
//            InputStream inputStream = multipartFile.getInputStream();
//            //构建日期目录
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
//            String datePath = dateFormat.format(new Date());
//            //获取文件名
//            String originname = multipartFile.getOriginalFilename();
//            System.out.println(originname);
//            originname = String.valueOf(UUID.randomUUID()) + ".PNG";
//            String fileUrl = dir + "/" + datePath + "/" + originname;
//            System.out.println(fileUrl);
//            //文件上传到云服务器
//            ossClient.putObject(bucketName, fileUrl, inputStream);
//
//            return "https://" + bucketName + "." + endpoint + "/" + fileUrl;
//        } catch (OSSException oe) {
//            System.out.println("Caught an OSSException, which means your request made it to OSS, "
//                    + "but was rejected with an error response for some reason.");
//            System.out.println("Error Message:" + oe.getErrorMessage());
//            System.out.println("Error Code:" + oe.getErrorCode());
//            System.out.println("Request ID:" + oe.getRequestId());
//            System.out.println("Host ID:" + oe.getHostId());
//        } catch (ClientException ce) {
//            System.out.println("Caught an ClientException, which means the client encountered "
//                    + "a serious internal problem while trying to communicate with OSS, "
//                    + "such as not being able to access the network.");
//            System.out.println("Error Message:" + ce.getMessage());
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "fail";
//        } finally {
//            if (ossClient != null) {
//                ossClient.shutdown();
//            }
//        }
//        return "success";
//    }
        try {
            // 获取文件的名称
            String fileName = multipartFile.getOriginalFilename();
            fileName =  String.valueOf(UUID.randomUUID()) + ".PNG";
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            // 调用oss的方法实现长传
            // 第一个参数 bucketName
            // 第二个参数 上传到oss的文件路径和文件名称
            ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(multipartFile.getBytes()), objectMetadata);
            // 关闭OSSClient。
            ossClient.shutdown();
            // 把上传的文件路径返回 （手动拼接）
            // 这里设置图片有效时间 我设置了30年
            Date expiration = new Date(System.currentTimeMillis() + 946080000 * 1000);
            String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @Override
    public boolean deleteImages(String fileUrl) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tKqDq4HjvVTRL1Uigcg";
        String accessKeySecret = "OPpkrPJf3pKGkGVY2vaOCNswJqmQgP";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "zhnfyxt";
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String imgFile = fileUrl.replace("https://bucket-ans.oss-cn-hangzhou.aliyuncs.com/", "");
        String fileName = imgFile.substring(0, imgFile.indexOf("?"));

        // 根据BucketName,objectName删除文件
        ossClient.deleteObject(bucketName, fileName);
        ossClient.shutdown();
        return true;
    }
    // 实现图片的预览功能
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }

}
